package com.yc.qunxing.service;

import com.alibaba.fastjson.JSON;
import com.yc.qunxing.clients.DriverAction;
import com.yc.qunxing.entity.DriverVehicles;
import com.yc.qunxing.entity.Drivers;
import com.yc.qunxing.entity.Orders;
import com.yc.qunxing.result.Result;
import com.yc.qunxing.websocket.WebSocketServer;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class OrderConsumer {

    @Autowired
    private IOrdersService iOrdersService;
    @Autowired
    private DriverAction driverAction;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitListener(queues = "orderQueue")
    public void receiveOrder(Map<String, Object> message) {
        int type = (int) message.get("type");
        switch (type) {
            case 1:
                handleOrder(message);
                break;
            case 2:
                handleAcceptOrder(message);
                break;
            case 3:
                handleCancelOrder(message);
                break;
            default:
                System.out.println("Unknown message type: " + type);
        }
    }

    private void handleOrder(Map<String, Object> orderMap) {
        // 处理订单提醒
        System.out.println("Received new order: " + orderMap);
    }

    private void handleAcceptOrder(Map<String, Object> orderMap) {
        // 接单逻辑
        Integer orderId = (Integer) orderMap.get("orderId");
        Integer driverId = (Integer) orderMap.get("driverId");
        Orders orders = iOrdersService.getById(orderId);
        if (orders != null) {
            String key = "order_lock:" + orderId;
            Boolean success = redisTemplate.opsForValue().setIfAbsent(key, driverId.toString());
            if (Boolean.TRUE.equals(success)) {
                orders.setStatus("2");
                orders.setDriverId(driverId);
                Drivers driver1 = new Drivers();
                driver1.setId(driverId);
                driver1.setStatus("2");
                driverAction.UpdateDriverStatus(driver1);
                iOrdersService.updateById(orders);
                Result<Drivers> driversResult = driverAction.GetById(driverId);
                Result<DriverVehicles> driverVehiclesResult = driverAction.GetVerById(driverId);
                
                Map<String, Object> map = new HashMap<>();
                map.put("type", 2); // 消息类型，2表示接单提醒
                map.put("orderId", orders.getOrderId());
                map.put("phoneNumber", driversResult.getData().getPhoneNumber());
                map.put("licensePlate", driversResult.getData().getLicensePlate());
                map.put("vehicleType", driverVehiclesResult.getData().getVehicleType());
                map.put("color", driverVehiclesResult.getData().getColor());
                map.put("driverName", driversResult.getData().getUsername());
                
                // 通过 WebSocket 向用户推送消息
                webSocketServer.sendToUsers(JSON.toJSONString(map));
            }
        }
    }

    private void handleCancelOrder(Map<String, Object> orderMap) {
        // 取消订单逻辑
        Integer orderId = (Integer) orderMap.get("orderId");
        Orders order = iOrdersService.getById(orderId);
        if (order != null) {
            order.setStatus("4");
            iOrdersService.updateById(order);
            System.out.println("Order cancelled: " + orderId);
        }
    }
}
